import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_pangle/flutter_pangle.dart';
import 'dart:io';

/// Pangle SDK 配置
class PangleConfig {
  static String get appId => Platform.isAndroid ? '215000358' : '215000358';
  static String get vodAppId => Platform.isAndroid ? '568708' : '997313';
  static String get securityKey => 'd31d3d35720f63d030e38b47edc7a9f3';
  static String get licensePath =>
      Platform.isAndroid ? 'vod_player.lic' : 'l-2295-ch-vod-a-886597.lic';

  /// 创建 SDK 配置对象
  static PAGSSDKConfig createSDKConfig({String? userId, bool debug = true}) {
    return PAGSSDKConfig(
      appId: appId,
      vodAppId: vodAppId,
      securityKey: securityKey,
      licenseAssertPath: licensePath,
      userId: userId ?? 'demo_user_123',
      debug: debug,
    );
  }
}

void main() {
  runApp(const MyApp());
  // 在应用启动后预热播放器引擎（可选，后台执行，不影响启动速度）
  _warmUpPlayerEngine();
}

/// 预热播放器引擎
/// 在应用启动后延迟执行，避免影响启动速度
void _warmUpPlayerEngine() {
  // 延迟2秒后预热，确保应用已经启动完成
  Future.delayed(const Duration(seconds: 2), () {
    final pangle = FlutterPangle();
    // 预热操作在后台执行，失败也不影响正常使用
    pangle.warmUpPlayerEngine().catchError((e) {
      // 忽略错误
    });
  });
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(title: 'Flutter Pangle Demo', home: RootTabs());
  }
}

class RootTabs extends StatefulWidget {
  const RootTabs({super.key});

  @override
  State<RootTabs> createState() => _RootTabsState();
}

class _RootTabsState extends State<RootTabs> {
  int _currentIndex = 0;
  final _pages = const [
    PangleDemoPage(),
    DefaultListPlayPage(),
    VerticalStreamPlayPage(),
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: _pages[_currentIndex],
      bottomNavigationBar: BottomNavigationBar(
        currentIndex: _currentIndex,
        onTap: (i) => setState(() => _currentIndex = i),
        items: const [
          BottomNavigationBarItem(icon: Icon(Icons.home), label: '首页'),
          BottomNavigationBarItem(icon: Icon(Icons.play_circle), label: '播放'),
          BottomNavigationBarItem(icon: Icon(Icons.view_stream), label: '上下滑'),
        ],
      ),
    );
  }
}

class PangleDemoPage extends StatefulWidget {
  const PangleDemoPage({super.key});

  @override
  State<PangleDemoPage> createState() => _PangleDemoPageState();
}

class _PangleDemoPageState extends State<PangleDemoPage> {
  final FlutterPangle _flutterPangle = FlutterPangle();
  final ScrollController _scrollController = ScrollController();

  bool _isSDKInitialized = false;
  String _logText = '等待操作...\n';

  @override
  void initState() {
    super.initState();
    _initializeSDK();
  }

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }

  void _addLog(String message) {
    setState(() {
      _logText += '${DateTime.now().toString().substring(11, 19)}: $message\n';
    });
    print('[PangleDemo] $message');
    // 自动滚动到底部
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (_scrollController.hasClients) {
        _scrollController.animateTo(
          _scrollController.position.maxScrollExtent,
          duration: const Duration(milliseconds: 300),
          curve: Curves.easeOut,
        );
      }
    });
  }

  // 初始化SDK
  Future<void> _initializeSDK() async {
    _addLog('开始初始化SDK...');
    try {
      final config = PangleConfig.createSDKConfig();

      final success = await _flutterPangle.initializeSDK(config);
      if (success) {
        _addLog('✓ SDK初始化成功');
        setState(() {
          _isSDKInitialized = true;
        });

        // 设置合规设置
        await _flutterPangle.setEligibleAudience(true);
        _addLog('✓ 设置合规设置: true');

        // 设置内容语言
        final currentLanguage = _flutterPangle.getCurrentLanguage();
        _addLog('当前设备语言: $currentLanguage');

        await _flutterPangle.setContentLanguages(['zh_hans', 'en']);
        _addLog('✓ 设置内容语言: [zh_hans, en]');

        // SDK初始化成功后，预热播放器引擎
        _flutterPangle.warmUpPlayerEngine().catchError((e) {
          // 忽略错误，预热失败不影响正常使用
        });
      } else {
        _addLog('✗ SDK初始化失败');
      }
    } catch (e) {
      _addLog('✗ SDK初始化异常: $e');
    }
  }

  // 获取默认短剧列表
  Future<void> _requestFeedList() async {
    if (!_isSDKInitialized) {
      _addLog('✗ SDK未初始化，请先初始化SDK');
      return;
    }

    _addLog('开始获取默认短剧列表...');
    try {
      final response = await _flutterPangle.requestFeedList(
        index: 1,
        count: 10,
      );

      _addLog('✓ 获取成功，共 ${response.list.length} 条');
      _addLog('是否有更多: ${response.hasMore}');

      for (var short in response.list) {
        _addLog('  - ${short.title} (ID: ${short.id})');
        _addLog('    描述: ${short.desc}');
        _addLog('    总集数: ${short.total}');
        _addLog('    总收藏数: ${short.totalCollectCount}');
      }

      if (response.error != null) {
        _addLog('警告: ${response.error}');
      }
    } catch (e) {
      _addLog('✗ 获取失败: $e');
    }
  }

  // 获取热门短剧列表
  Future<void> _requestPopularDrama() async {
    if (!_isSDKInitialized) {
      _addLog('✗ SDK未初始化');
      return;
    }

    _addLog('开始获取热门短剧列表...');
    try {
      final response = await _flutterPangle.requestPopularDrama(
        index: 1,
        count: 10,
      );

      _addLog('✓ 获取成功，共 ${response.list.length} 条');
      for (var short in response.list) {
        _addLog('  - ${short.title} (ID: ${short.id})');
      }
    } catch (e) {
      _addLog('✗ 获取失败: $e');
    }
  }

  // 获取新剧列表
  Future<void> _requestNewFeedList() async {
    if (!_isSDKInitialized) {
      _addLog('✗ SDK未初始化');
      return;
    }

    _addLog('开始获取新剧列表...');
    try {
      final response = await _flutterPangle.requestNewFeedList(
        index: 1,
        count: 10,
      );

      _addLog('✓ 获取成功，共 ${response.list.length} 条');
      for (var short in response.list) {
        _addLog('  - ${short.title} (ID: ${short.id})');
      }
    } catch (e) {
      _addLog('✗ 获取失败: $e');
    }
  }

  // 获取指定分类的列表
  Future<void> _requestFeedListWithFilters() async {
    if (!_isSDKInitialized) {
      _addLog('✗ SDK未初始化');
      return;
    }

    _addLog('开始获取指定分类的列表（男频）...');
    try {
      final response = await _flutterPangle.requestFeedListWithFilters(
        index: 1,
        count: 10,
        categoryIds: [2], // 1 = 男频
      );

      _addLog('✓ 获取成功，共 ${response.list.length} 条');
      for (var short in response.list) {
        _addLog('  - ${short.title} (ID: ${short.id})');
      }
    } catch (e) {
      _addLog('✗ 获取失败: $e');
    }
  }

  // 获取指定标签的列表（收藏榜）
  Future<void> _requestDramaWithTag() async {
    if (!_isSDKInitialized) {
      _addLog('✗ SDK未初始化');
      return;
    }

    _addLog('开始获取收藏榜列表...');
    try {
      final response = await _flutterPangle.requestDramaWithTag(
        tag: 4, // 4 = 收藏榜
        index: 1,
        count: 10,
      );

      _addLog('✓ 获取成功，共 ${response.list.length} 条');
      for (var short in response.list) {
        _addLog('  - ${short.title} (ID: ${short.id})');
      }
    } catch (e) {
      _addLog('✗ 获取失败: $e');
    }
  }

  // 获取分类列表
  Future<void> _getCategoryList() async {
    if (!_isSDKInitialized) {
      _addLog('✗ SDK未初始化');
      return;
    }

    _addLog('开始获取分类列表...');
    try {
      final categories = await _flutterPangle.getCategoryList('zh_hans');

      _addLog('✓ 获取成功，共 ${categories.length} 个分类');
      for (var category in categories) {
        _addLog('  - ${category.categoryName} (ID: ${category.categoryId})');
      }
    } catch (e) {
      _addLog('✗ 获取失败: $e');
    }
  }

  // 搜索短剧
  Future<void> _requestSearchDrama() async {
    if (!_isSDKInitialized) {
      _addLog('✗ SDK未初始化');
      return;
    }

    _addLog('开始搜索短剧（关键词: 爱情）...');
    try {
      final response = await _flutterPangle.requestSearchDrama(
        index: 1,
        count: 10,
        keyword: '爱情',
        isFuzzy: true,
      );

      _addLog('✓ 搜索成功，共 ${response.list.length} 条');
      for (var short in response.list) {
        _addLog('  - ${short.title} (ID: ${short.id})');
      }
    } catch (e) {
      _addLog('✗ 搜索失败: $e');
    }
  }

  // 检查播放状态
  Future<void> _checkPlayStatus() async {
    if (!_isSDKInitialized) {
      _addLog('✗ SDK未初始化');
      return;
    }

    _addLog('开始检查播放状态...');
    try {
      final status = await _flutterPangle.checkPlayStatus();
      String statusText;
      switch (status) {
        case 0:
          statusText = '未知';
          break;
        case 1:
          statusText = '支持播放';
          break;
        case 2:
          statusText = '不支持播放';
          break;
        default:
          statusText = '未知状态 ($status)';
      }
      _addLog('✓ 播放状态: $statusText');
    } catch (e) {
      _addLog('✗ 检查失败: $e');
    }
  }

  // 设置收藏
  Future<void> _setCollected() async {
    if (!_isSDKInitialized) {
      _addLog('✗ SDK未初始化');
      return;
    }

    _addLog('开始设置收藏状态（示例ID: 123456）...');
    try {
      final success = await _flutterPangle.setCollected(
        collected: true,
        shortplayId: 123456,
      );

      if (success) {
        _addLog('✓ 收藏设置成功');
      } else {
        _addLog('✗ 收藏设置失败');
      }
    } catch (e) {
      _addLog('✗ 设置失败: $e');
    }
  }

  // 清除缓存
  Future<void> _clearLocalCache() async {
    if (!_isSDKInitialized) {
      _addLog('✗ SDK未初始化');
      return;
    }

    _addLog('开始清除本地缓存...');
    try {
      await _flutterPangle.clearLocalCache();
      _addLog('✓ 缓存清除成功');
    } catch (e) {
      _addLog('✗ 清除失败: $e');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Flutter Pangle Demo'),
        actions: [
          IconButton(
            icon: const Icon(Icons.clear),
            onPressed: () {
              setState(() {
                _logText = '日志已清空\n';
              });
            },
            tooltip: '清空日志',
          ),
        ],
      ),
      body: Column(
        children: [
          // 操作按钮区域
          Container(
            padding: const EdgeInsets.all(8.0),
            color: Colors.grey[200],
            child: SingleChildScrollView(
              child: Wrap(
                spacing: 8.0,
                runSpacing: 8.0,
                children: [
                  _buildActionButton(
                    '初始化SDK',
                    _initializeSDK,
                    icon: Icons.settings,
                  ),
                  _buildActionButton(
                    '获取默认列表',
                    _requestFeedList,
                    enabled: _isSDKInitialized,
                  ),
                  _buildActionButton(
                    '获取热门',
                    _requestPopularDrama,
                    enabled: _isSDKInitialized,
                  ),
                  _buildActionButton(
                    '获取新剧',
                    _requestNewFeedList,
                    enabled: _isSDKInitialized,
                  ),
                  _buildActionButton(
                    '分类筛选',
                    _requestFeedListWithFilters,
                    enabled: _isSDKInitialized,
                  ),
                  _buildActionButton(
                    '收藏榜',
                    _requestDramaWithTag,
                    enabled: _isSDKInitialized,
                  ),
                  _buildActionButton(
                    '获取分类',
                    _getCategoryList,
                    enabled: _isSDKInitialized,
                  ),
                  _buildActionButton(
                    '搜索',
                    _requestSearchDrama,
                    enabled: _isSDKInitialized,
                  ),
                  _buildActionButton(
                    '检查播放',
                    _checkPlayStatus,
                    enabled: _isSDKInitialized,
                  ),
                  _buildActionButton(
                    '设置收藏',
                    _setCollected,
                    enabled: _isSDKInitialized,
                  ),
                  _buildActionButton(
                    '清除缓存',
                    _clearLocalCache,
                    enabled: _isSDKInitialized,
                  ),
                ],
              ),
            ),
          ),
          // 日志显示区域
          Expanded(
            child: Container(
              margin: const EdgeInsets.all(8.0),
              padding: const EdgeInsets.all(12.0),
              decoration: BoxDecoration(
                color: Colors.black87,
                borderRadius: BorderRadius.circular(8.0),
                border: Border.all(color: Colors.grey[800]!),
              ),
              child: SingleChildScrollView(
                controller: _scrollController,
                child: Text(
                  _logText,
                  style: const TextStyle(
                    color: Colors.green,
                    fontFamily: 'monospace',
                    fontSize: 12.0,
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildActionButton(
    String label,
    VoidCallback onPressed, {
    IconData? icon,
    bool enabled = true,
  }) {
    return ElevatedButton.icon(
      onPressed: enabled ? onPressed : null,
      icon: Icon(icon ?? Icons.play_arrow, size: 18),
      label: Text(label),
      style: ElevatedButton.styleFrom(
        padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
      ),
    );
  }
}

/// 默认列表播放页
class DefaultListPlayPage extends StatefulWidget {
  const DefaultListPlayPage({super.key});

  @override
  State<DefaultListPlayPage> createState() => _DefaultListPlayPageState();
}

class _DefaultListPlayPageState extends State<DefaultListPlayPage> {
  final FlutterPangle _pangle = FlutterPangle();
  bool _inited = false;
  bool _loading = false;
  List<PAGSShort> _list = [];
  String _msg = '';

  Future<void> _ensureInit() async {
    if (_inited) return;
    setState(() => _loading = true);
    try {
      final ok = await _pangle.initializeSDK(PangleConfig.createSDKConfig());
      if (ok) {
        await _pangle.setEligibleAudience(true);
        await _pangle.setContentLanguages(['zh_hans', 'en']);
        _inited = true;
        // SDK初始化成功后，预热播放器引擎
        _pangle.warmUpPlayerEngine().catchError((e) {
          // 忽略错误，预热失败不影响正常使用
        });
      } else {
        _msg = 'SDK初始化失败';
      }
    } catch (e) {
      _msg = '初始化异常: $e';
    } finally {
      setState(() => _loading = false);
    }
  }

  Future<void> _load() async {
    await _ensureInit();
    if (!_inited) return;
    setState(() => _loading = true);
    try {
      final resp = await _pangle.requestFeedList(index: 1, count: 10);
      setState(() {
        _list = resp.list;
        _msg = '共 ${resp.list.length} 条，hasMore=${resp.hasMore}';
      });
    } catch (e) {
      setState(() => _msg = '拉取失败: $e');
    } finally {
      setState(() => _loading = false);
    }
  }

  void _openPlayer(PAGSShort item) async {
    // 在后台线程进行JSON编码，避免阻塞主线程
    final jsonStr = await Future(() => jsonEncode(item.toMap()));

    if (!mounted) return;

    Navigator.of(context).push(
      MaterialPageRoute(
        builder: (_) => Scaffold(
          // appBar: AppBar(title: const Text('播放页')),
          body: PangleDetailAndroidView(
            shortplayJson: jsonStr,
            controller: PangleDetailController(
              autoPlay: true,
              playSingleItem: false,
              initialPlayIndex: 3,
            ),
          ),
        ),
      ),
    );
  }

  @override
  void initState() {
    super.initState();
    _load();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('默认列表播放')),
      body: _loading
          ? const Center(child: CircularProgressIndicator())
          : Column(
              children: [
                if (_msg.isNotEmpty)
                  Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: Text(_msg),
                  ),
                Expanded(
                  child: ListView.separated(
                    itemCount: _list.length,
                    separatorBuilder: (_, __) => const Divider(height: 1),
                    itemBuilder: (ctx, i) {
                      final it = _list[i];
                      print('body:${_list[i].coverImage}');
                      return ListTile(
                        title: Text(it.title ?? ''),
                        subtitle: Text('ID: ${it.id}  总集: ${it.total}'),
                        trailing: TextButton(
                          onPressed: () => _openPlayer(it),
                          child: const Text('播放'),
                        ),
                      );
                    },
                  ),
                ),
              ],
            ),
    );
  }
}

/// 上下滑播放页（使用多个 AndroidView 组成纵向 PageView）
class VerticalStreamPlayPage extends StatefulWidget {
  const VerticalStreamPlayPage({super.key});

  @override
  State<VerticalStreamPlayPage> createState() => _VerticalStreamPlayPageState();
}

class _VerticalStreamPlayPageState extends State<VerticalStreamPlayPage> {
  final FlutterPangle _pangle = FlutterPangle();
  final PageController _pageController = PageController();
  bool _inited = false;
  bool _loading = false;
  List<PAGSShort> _list = [];
  int _currentPage = 0;
  int _pageIndex = 1;
  bool _hasMore = true;
  bool _loadingMore = false;
  // 预计算的 JSON 缓存，避免重复序列化
  final Map<int, String> _jsonCache = {};
  // 每个页面的原生控制器
  final Map<int, PangleDetailController> _controllers = {};
  // 当前进度（秒）与总时长（秒）
  double _progressSec = 0;
  double _durationSec = 0;
  double? _draggingSec;

  Future<void> _ensureInit() async {
    if (_inited) return;
    setState(() => _loading = true);
    try {
      final ok = await _pangle.initializeSDK(PangleConfig.createSDKConfig());
      if (ok) {
        await _pangle.setEligibleAudience(true);
        await _pangle.setContentLanguages(['zh_hans', 'en']);
        _inited = true;
        // SDK初始化成功后，预热播放器引擎
        // _pangle.warmUpPlayerEngine().catchError((e) {
        //   // 忽略错误，预热失败不影响正常使用
        // });
      }
    } finally {
      setState(() => _loading = false);
    }
  }

  Future<void> _load({bool append = false}) async {
    await _ensureInit();
    if (!_inited) return;
    if (append && _loadingMore) return;
    if (append) {
      setState(() => _loadingMore = true);
    } else {
      setState(() => _loading = true);
    }
    try {
      final resp = await _pangle.requestFeedList(index: _pageIndex, count: 20);
      setState(() {
        if (append) {
          _list.addAll(resp.list);
        } else {
          _list = resp.list;
        }
        _hasMore = resp.hasMore;
        _pageIndex++;
        // 预计算 JSON
        for (
          var i = append ? _list.length - resp.list.length : 0;
          i < _list.length;
          i++
        ) {
          _jsonCache[i] = jsonEncode(_list[i].toMap());
        }
      });
    } finally {
      setState(() {
        _loading = false;
        _loadingMore = false;
      });
    }
  }

  void _onPageChanged(int index) {
    setState(() => _currentPage = index);
    // 切页重置可视化进度
    _progressSec = 0;
    _durationSec = 0;
    _draggingSec = null;

    // 暂停之前页面的播放并标记为非当前Fragment
    for (int i = 0; i < _controllers.length; i++) {
      if (i != index && _controllers[i] != null) {
        _controllers[i]!.setCurrentFragment(false);
        _controllers[i]!.pause();
      }
    }
    // 开始播放当前页面
    if (_controllers[index] != null) {
      _controllers[index]!.setCurrentFragment(true);
      _controllers[index]!.play();
      _controllers[index]!.autoPlay = false;
    }

    // 预加载：当接近末尾时加载更多
    if (index >= _list.length - 3 && _hasMore && !_loadingMore) {
      _load(append: true);
    }
  }

  @override
  void initState() {
    super.initState();
    _load();
    // PageView初始化时会自动触发onPageChanged，但需要确保在数据加载完成后才播放
    // 使用addPostFrameCallback确保在第一个页面渲染完成后播放
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (_controllers.isNotEmpty &&
          _controllers[0] != null &&
          _list.isNotEmpty) {
        // 延迟一点时间确保preLoadVideo完成
        Future.delayed(const Duration(milliseconds: 300), () {
          if (_controllers[0] != null) {
            _controllers[0]!.setCurrentFragment(true);
            _controllers[0]!.play();
            _controllers[0]!.autoPlay = false;
          }
        });
      }
    });
  }

  @override
  void dispose() {
    _pageController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    if (_loading) {
      return Scaffold(
        appBar: AppBar(title: const Text('上下滑播放')),
        body: const Center(child: CircularProgressIndicator()),
      );
    }
    return Scaffold(
      // appBar: AppBar(title: const Text('上下滑播放')),
      body: _list.isEmpty
          ? const Center(child: Text('暂无数据'))
          : Stack(
              children: [
                PageView.builder(
                  controller: _pageController,
                  scrollDirection: Axis.vertical,
                  // PageView 默认会预加载前后各 1 页
                  itemCount: _list.length,
                  onPageChanged: _onPageChanged,
                  itemBuilder: (ctx, i) {
                    // 使用缓存的 JSON，避免重复序列化
                    final jsonStr =
                        _jsonCache[i] ?? jsonEncode(_list[i].toMap());
                    if (_jsonCache[i] == null) {
                      _jsonCache[i] = jsonStr;
                    }
                    final controller = _controllers[i] ??=
                        PangleDetailController(
                          autoPlay: i == _currentPage,
                          playSingleItem: true,
                          onEvent: (event, data) {
                            if (_currentPage != i) return;
                            if (event == 'onProgressChange') {
                              // 兜底单位：若值很大，按毫秒转秒
                              final p = (data['progress'] ?? 0) as int;
                              final d = (data['duration'] ?? 0) as int;
                              double ps = p.toDouble();
                              double ds = d.toDouble();
                              if (ps > 36000) ps = ps / 1000.0;
                              if (ds > 36000) ds = ds / 1000.0;
                              setState(() {
                                if (_draggingSec == null) {
                                  _progressSec = ps.clamp(0, ds <= 0 ? ps : ds);
                                }
                                _durationSec = ds <= 0 ? _durationSec : ds;
                              });
                            }
                          },
                        );
                    if (i == _currentPage && controller.autoPlay) {
                      controller.autoPlay = false;
                      WidgetsBinding.instance.addPostFrameCallback((_) {
                        if (_controllers[i] != null) {
                          _controllers[i]!
                            ..setCurrentFragment(true)
                            ..play();
                        }
                      });
                    }
                    return PangleDetailAndroidView(
                      shortplayJson: jsonStr,
                      controller: controller,
                    );
                  },
                ),
                // 底部进度条
                if (_durationSec > 0)
                  Positioned(
                    left: 0,
                    right: 0,
                    bottom: 12,
                    child: Padding(
                      padding: const EdgeInsets.symmetric(horizontal: 16),
                      child: Row(
                        children: [
                          Text(
                            _fmtTime((_draggingSec ?? _progressSec).toInt()),
                            style: const TextStyle(
                              color: Colors.white70,
                              fontSize: 12,
                            ),
                          ),
                          Expanded(
                            child: SliderTheme(
                              data: SliderTheme.of(context).copyWith(
                                trackHeight: 2,
                                thumbShape: const RoundSliderThumbShape(
                                  enabledThumbRadius: 6,
                                ),
                              ),
                              child: Slider(
                                min: 0,
                                max: _durationSec <= 0 ? 1 : _durationSec,
                                value: (_draggingSec ?? _progressSec).clamp(
                                  0,
                                  _durationSec <= 0 ? 1 : _durationSec,
                                ),
                                onChanged: (v) {
                                  setState(() => _draggingSec = v);
                                },
                                onChangeEnd: (v) {
                                  final c = _controllers[_currentPage];
                                  if (c != null) {
                                    c.seekToSeconds(v.toInt());
                                  }
                                  setState(() {
                                    _progressSec = v;
                                    _draggingSec = null;
                                  });
                                },
                              ),
                            ),
                          ),
                          Text(
                            _fmtTime(_durationSec.toInt()),
                            style: const TextStyle(
                              color: Colors.white70,
                              fontSize: 12,
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
              ],
            ),
    );
  }

  String _fmtTime(int sec) {
    final s = sec % 60;
    final m = (sec ~/ 60) % 60;
    final h = (sec ~/ 3600);
    String two(int n) => n.toString().padLeft(2, '0');
    if (h > 0) return '${two(h)}:${two(m)}:${two(s)}';
    return '${two(m)}:${two(s)}';
  }
}
